import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Grid, Form, Button, Select,Table,Pagination,Icon,Feedback } from '@icedesign/base';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import {hashHistory} from 'react-router';
import DataBinder from '@icedesign/data-binder';
import EditRoles from '../EditRoles'
import ConfirmDeleteDialog from '../../../Dialog/components/ConfirmDeleteDialog'

const { Row, Col } = Grid;
const FormItem = Form.Item;
@DataBinder({
  tableData: {
    url: '/account/api/roles',
    params: {
      page: 1,
      pageSize:10,
    },
    responseFormatter: (responseHandler, res, originResponse) => {
      // 做一些数据转换
      if(res.msg=="请登录!" && res.code==401){
        Feedback.toast.error(res.msg)
        setTimeout(()=>{
          hashHistory.push('/login');
        },1000)
        return;
        
      }else if(res.code !==200){
        Feedback.toast.error(res.msg);
        return;
      }
      const newRes = {
        status: res.code == 200 ? 'SUCCESS' : 'ERROR',
        message: res.msg,
        data:(res.code==200)?(res.data):{},
        page:(res.code==200)?(res.data.page):1,
      };
      
      
      // 回传给处理函数
      // 不做回传处理会导致数据更新逻辑中断
      responseHandler(newRes, originResponse);
    },
    defaultBindingData: {
      page:1,
      pageSize:10,
    },
  }
})


export default class ListRoles extends Component {
  static displayName = 'ListRoles';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      value: {
        title: '',
        desc: '',
        author: '',
        body: null,
        cats: [],
        current:1,
      },
    };
  }

  componentDidMount() {
    this.fetchData({
      page: 1
    });
   
  }

  changePage = (currentPage) => {
    this.setState({current:currentPage})
    //翻页
    this.fetchData({
      page: currentPage,
    });
  };

  fetchData = ({ page }) => {
    this.props.updateBindingData('tableData', {
      params: {
        page
      },
    },(res)=>{
      if(res.code== 200 && res.success){
        let rows = res.data.rows;
      }else if(res.code==401 && res.msg=='请登录!'){
        Feedback.toast.error(res.msg)
        setTimeout(()=>{
          hashHistory.push('/login');
        },3000)
        return;
      }else{
        Feedback.toast.error(res.msg)
      }
    });
  }
  onOpen=(record,type)=>{
    
    //record: 编辑时record为当前行的数据记录，添加时为空
    //type: edit编辑 add 添加
    console.log(type)
    this.refs.getOpenDialog.onOpen(record,type);
  }

  onDelete = (record)=>{
    //record: 为当前行的数据记录，添加时为空
    let id = record.id;     //当前记录id
    let url = '/api/company/' //url
    this.refs.getDeleteButton.onOpen({id},url);
  }
  renderOperations = (value,index,record) =>{
    return (
      <div className="operation-table-operation" style={styles.operationTable}>
        <span
          onClick={this.onOpen.bind(this,record,'edit')}
          title="编辑"
          style={styles.operBtn}
        >
          <Icon size="xs" type="edit" />
        </span>
        <span title="删除" style={styles.operBtn} onClick={this.onDelete.bind(this,record)}>
          <Icon size="xs" type="close" />
        </span>
       
      </div>
    );
  }
  freshData = (status) =>{
    if(status){
      //保存成功
      let page = this.state.current;
      this.fetchData({page})
    }
  }

  render() {
    const tableData = this.props.bindingData.tableData;
    return (
        <IceContainer>
            <div>
              <Button  type="primary" onClick={this.onOpen.bind(this,'','add')}>增加</Button>&emsp;
        {/* <Button  type="primary" onclick={this.changeStatus.bind(this)}>启用/禁用</Button> */}
          <EditRoles ref="getOpenDialog" onSaveChange={this.freshData}/>
          </div>
            <Table
            filterMode = "single"
            className="basic-table"
            style={styles.basicTable}
            dataSource={tableData.rows}
            hasBorder={false}
          >
            <Table.Column title="角色名" dataIndex="name"  width={100} align="center" />
            <Table.Column  title="所属公司" dataIndex="company" width={140} align="center" cell={(value)=>{return value.companyName}} />
            <Table.Column title="创建时间" dataIndex="createdTime"  width={100} align="center" />
            {/* <Table.Column title="编号" dataIndex="code"  width={80} align="center" /> */}
            <Table.Column title="操作" dataIndex="operation" width={120} align="center" cell={this.renderOperations} />
          </Table>
          <div style={styles.paginationContainer}>
            <Pagination
              current={tableData.page}
              pageSize={tableData.pageSize}
              total={tableData.totalCount}
              onChange={this.changePage.bind(this)}
            />
          </div>
          <ConfirmDeleteDialog  ref="getDeleteButton" onChange={this.freshData}/>
          
        </IceContainer>
       
    );
  }
}

const styles = {
  form: {
    marginTop: 30,
  },
  cats: {
    width: '100%',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
  },
};
